/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.easyedu.dictionary.gui.actions;

import eu.easyedu.dictionary.api.model.Dictionary;
import eu.easyedu.dictionary.api.model.Language;
import eu.easyedu.dictionary.api.model.Relationship;
import eu.easyedu.dictionary.api.model.Word;
import eu.easyedu.dictionary.api.model.WordRelationship;
import eu.easyedu.dictionary.api.nservice.spi.WordBookService;
import eu.easyedu.dictionary.gui.resources.Bundle;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Item;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;

/**
 *
 * @author hlavki
 */
public class ImportDictionaryAction extends AbstractAction implements LookupListener, ContextAwareAction {

    private static final long serialVersionUID = 1L;
    private Lookup context;
    private Lookup.Result<Dictionary> lookupResult;
    private WordBookService wbService;

    public ImportDictionaryAction() {
        this(Utilities.actionsGlobalContext());
        wbService = Lookup.getDefault().lookup(WordBookService.class);
    }

    private ImportDictionaryAction(Lookup context) {
        super(Bundle.getMessage("ImportDictionaryAction.text"));
        this.context = context;
    }

    void init() {
        assert SwingUtilities.isEventDispatchThread() : "this shall be called just from AWT thread";
        if (lookupResult != null) {
            return;
        }
        Lookup.Template<Dictionary> tpl = new Lookup.Template<Dictionary>(Dictionary.class);
        lookupResult = context.lookup(tpl);
        lookupResult.addLookupListener(this);
        resultChanged(null);
    }

    public void actionPerformed(ActionEvent e) {
        init();
        Collection<? extends Item<Dictionary>> items = lookupResult.allItems();
        Dictionary dictionary = items.iterator().next().getInstance();
        importDictionary("/data/home/hlavki/download/en-sk.txt", dictionary);
    }

    public Action createContextAwareInstance(Lookup actionContext) {
        return new ImportDictionaryAction(actionContext);
    }

    public void resultChanged(LookupEvent ev) {

    }

    WordItem getWord(String record) {
        String word = record;
        String type = null;
        if (record.contains("(")) {
            int idx = record.indexOf('(');
            word = record.substring(0, idx);
            type = record.substring(idx + 1, idx + 2);
        }
        return new WordItem(word.trim(), type);
    }

    void importDictionary(String filename, Dictionary dictionary) {
        BufferedReader reader = null;
        Language sourceLang = wbService.getLanguage(dictionary, "ENG");
        Language targetLang = wbService.getLanguage(dictionary, "SKK");
        try {
            reader = new BufferedReader(new FileReader(filename));
            String line = null;
            while ((line = reader.readLine()) != null) {
                StringTokenizer tokenizer = new StringTokenizer(line, "\t");
                String[] mainDicision = line.split("\t");
                WordItem source = getWord(mainDicision[0]);
                String[] targets = mainDicision[1].split(",");
                List<Word> targetWords = new ArrayList<Word>(targets.length);
                for (String target : targets) {
                    targetWords.add(new Word(getWord(target).getWord(), targetLang));
                }
                Word srcWord = wbService.getWord(dictionary, source.getWord(), sourceLang);
                if (srcWord == null) {
                    srcWord = new Word(source.getWord(), sourceLang);
                }
                List<WordRelationship> relationships = new ArrayList<WordRelationship>();
                for (Word item : targetWords) {
                    Word trgWord = wbService.getWord(dictionary, item.getWord(), targetLang);
                    if (trgWord == null) {
                        trgWord = item;
                    }
                    relationships.add(new WordRelationship(srcWord, trgWord, Relationship.TRANSLATION));
                }
                for (Word item : targetWords) {
                    for (Word subItem : targetWords) {
                        if (!item.getWord().equals(subItem.getWord())) {
                            relationships.add(new WordRelationship(item, subItem, Relationship.SYNONYM));
                        }
                    }
                }
                System.out.println("Adding word " + srcWord + " with " + relationships.size() + " relationships");
                wbService.addWord(dictionary, srcWord, relationships);
            }
        } catch (IOException e) {

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {

                }
            }
        }
    }

    private static class WordItem {

        private final String word;
        private final String type;

        public WordItem(String word, String type) {
            this.word = word;
            this.type = type;
        }

        public String getType() {
            return type;
        }

        public String getWord() {
            return word;
        }

        @Override
        public String toString() {
            return word + (type != null ? " [" + type + "]" : "");
        }
    }
}
